package com.wq.code;

/**
 * @Author: wangqiang20995
 * @Date:19-2-17
 * @Description:
 * @Resource:
 */
public class Operation {

    public static void main(String args[]) {
        int i = 10, j = 20;
        System.out.println("二进制[i]：" + Integer.toBinaryString(i));

        System.out.println("二进制[j]：" + Integer.toBinaryString(j));

        System.out.println("i&j：" + (i & j) + " / 二进制[i&j]:" + Integer.toBinaryString(i & j));

        System.out.println("i|j：" + (i | j) + " / 二进制[i|j]:" + Integer.toBinaryString(i | j));

        System.out.println("i^j：" + (i ^ j) + " / 二进制[i^j]:" + Integer.toBinaryString(i ^ j));

        System.out.println("~j:" + ~j + " / 二进制[~j]:" + Integer.toBinaryString(~20));

        String number = "1010";

        System.out.println(Integer.toBinaryString(-10));

        System.out.println(transferFromBinary(number,true));

        System.out.println(transferFromBinary(number,false));

        System.out.println(-4 >>> 2);

    }

    private static int transferFromBinary(String number,boolean positive){
        if(number == null || number.isEmpty()){
            throw new IllegalArgumentException("wrong number");
        }

        if(positive){//正数
            int sum = 0;
            for(int i = 0;i<number.length();i++){
                int code = Integer.parseInt(String.valueOf(number.charAt(i)));
                sum += code << (number.length() - 1 -i);
            }
            return sum;
        }else {//负数
            StringBuilder builder = new StringBuilder(32);

            for(int i = 0 ;i<32 - number.length() ;i++){
                builder.append("1");
            }

            builder.append(number);

            return Integer.parseUnsignedInt(builder.toString(),2);
        }

    }
}
